package com.teichmann.core.targets;

import java.io.IOException;
import java.util.ArrayList;
import java.util.regex.Pattern;

import org.apache.http.HttpException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.htmlparser.Node;
import org.htmlparser.NodeFilter;
import org.htmlparser.Parser;
import org.htmlparser.Tag;
import org.htmlparser.lexer.Lexer;
import org.htmlparser.tags.LinkTag;
import org.htmlparser.tags.TableColumn;
import org.htmlparser.util.NodeList;
import org.htmlparser.util.ParserException;
import org.htmlparser.visitors.NodeVisitor;

import com.teichmann.bo.Car;
import com.teichmann.bo.Seller;
import com.teichmann.core.Page;
import com.teichmann.core.annotations.Delimiter;
import com.teichmann.core.annotations.Url;
import com.teichmann.core.util.ConnectionUtils;
import com.teichmann.core.util.CrawlerUtils;

@Url(value = "http://www.rcveiculos.com/seminovos.asp")
@Delimiter(tag="tr" , attribute="valign", value="top")
public class RC implements Page {
	
	ArrayList<Car> cars = new ArrayList<Car>();

	NodeVisitor visitor = new NodeVisitor() {
		@Override
		public void visitTag(Tag tag) {
			String name = tag.getTagName();
			if ("tr".equalsIgnoreCase(name)
					&& (tag.getAttribute("class") != null
					&& ( tag.getAttribute("class").equalsIgnoreCase("Tabela")))) {
				cars.add(extractInformation(tag));
			}
		}
	};
	
	public ArrayList<Car> performSearch() throws IOException {

		// Read the response body.
		String responseBody =  ConnectionUtils.get(this.getClass().getAnnotation(Url.class).value());
		Parser parser = new Parser(new Lexer(responseBody));
		try {
			parser.visitAllNodesWith(visitor);
		} catch (ParserException e) {
			e.printStackTrace();
		}

		return cars;

	}
	
	
	public Car extractInformation(Tag line){
		Car car = new Car();
		try {
		
			NodeList details = line.getChildren();
			details = details.extractAllNodesThatMatch(new NodeFilter(){
				public boolean accept(Node arg0) {
					if (arg0 instanceof TableColumn) {
						return true;
						
					}
					return false;
				}
				
			});
			
			Pattern intOnly = Pattern.compile("\\d*");
			car.setModelo(CrawlerUtils.removeUnusedFields(details.elementAt(0).getChildren().elementAt(1).getChildren().elementAt(0).getText()));
			car.setAnoFabricacao(Integer.parseInt(CrawlerUtils.removeUnusedFields(details.elementAt(1).getChildren().elementAt(0).getText())));
			car.setAnoModelo(car.getAnoFabricacao());
			car.setCor(CrawlerUtils.removeUnusedFields(details.elementAt(2).getChildren().elementAt(0).getText()));
			car.setCombustivel(CrawlerUtils.removeUnusedFields(details.elementAt(3).getChildren().elementAt(0).getText()));
			car.setValor(CrawlerUtils.removeUnusedFields(details.elementAt(4).getChildren().elementAt(0).getText()));
			
			String link = ((LinkTag)details.elementAt(0).getChildren().elementAt(1)).getLink();
			link =  link.substring(link.indexOf("(")+1, link.indexOf(","));
			
			car.setUrl("http://www.rcveiculos.com/detalhe_veiculo.asp?TpDetalhe=I&Veiculo="+link);
			car.setRevenda(new Seller(this.getClass().getName()));

		} catch (Exception e) {
			e.printStackTrace();
		}

		return car;

	}
	
	private void addExtraInfo(final Car car) throws HttpException, IOException {
		HttpClient client = new DefaultHttpClient();
		HttpGet method = new HttpGet(car.getUrl());

		ResponseHandler<String> responseHandler = new BasicResponseHandler();
		String responseBody = client.execute(method, responseHandler);
		Parser parser = new Parser(new Lexer(responseBody));
		try {
			NodeVisitor photoVisitor = new NodeVisitor() {
				@Override
				public void visitTag(Tag tag) {
					String name = tag.getTagName();
					if ("img".equalsIgnoreCase(name)
							&& (tag.getAttribute("onclick") != null && tag.getAttribute(
									"onclick").contains("fu_rollover"))) {

						if (car.getFotos() == null) {
							car.setFotos(new ArrayList<String>());
						}

						int start = tag.getAttributeEx("onclick").getValue().indexOf("http://");
						int end  = tag.getAttributeEx("onclick").getValue().indexOf("');");
						car.getFotos().add(tag.getAttributeEx("onclick").getValue().substring(start,end));
					}
				}
			};
			parser.visitAllNodesWith(photoVisitor);

		} catch (ParserException e) {
			e.printStackTrace();
		}

	}



}
